﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXFramework.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
namespace WXFramework
{
    public class CropWXManager
    {
       
        #region 管理部门

        private const string getDepListUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={0}";
        private const string creatDepUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={0}";
        private const string updateDepUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={0}";
        private const string delDepUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={0}&id={1}";

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string GetDeprtmentList(string token)
        {
            return HttpHelper.HttpGet(string.Format(getDepListUrl, token));

        }

        /// <summary>
        /// 新增部门
        /// </summary>
        /// <param name="model"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string CreatDepartment(NewDepModel model,string token)
        {
            var url = string.Format(creatDepUrl,token);
            var content = JsonConvert.SerializeObject(model);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 更新部门
        /// </summary>
        /// <param name="model"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string UpdateDepartment(NewDepModel model, string token)
        {
            var url = string.Format(updateDepUrl, token);
            var content = JsonConvert.SerializeObject(model);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="id"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string DelDepartment(string id, string token)
        {
            return HttpHelper.HttpGet(string.Format(delDepUrl, token, id));
        }

        #endregion

        #region 管理用户
        private const string creatUserUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={0}";
        private const string updateUserUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token={0}";
        private const string delUserUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token={0}&userid={1}";
        private const string getUserInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={0}&userid={1}";
        private const string getDepUsersInfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={0}&department_id={1}&fetch_child={2}&status={3}";

        /// <summary>
        /// 创建成员
        /// </summary>
        /// <param name="user"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string CreateUser(WXUserInfo user, string token)
        {
            var url = string.Format(creatUserUrl, token);
            var content = JsonConvert.SerializeObject(user);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 更新成员
        /// </summary>
        /// <param name="user"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string UpdateUser(WXUserInfo user, string token)
        {
            var url = string.Format(updateUserUrl, token);
            var content = JsonConvert.SerializeObject(user);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 删除成员
        /// </summary>
        /// <param name="id"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string DelUser(string id, string token)
        {
            return HttpHelper.HttpGet(string.Format(delUserUrl, token, id));
        }

        /// <summary>
        /// 获取成员
        /// </summary>
        /// <param name="id"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string GetUserInfo(string id, string token)
        {
            return HttpHelper.HttpGet(string.Format(getUserInfoUrl, token, id));
        }

        /// <summary>
        /// 获取成员
        /// </summary>
        /// <param name="id"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string GetUserInfo(string id)
        {
            return HttpHelper.HttpGet(string.Format(getUserInfoUrl, CropTokenManager.GetToken(), id));
        }



        /// <summary>
        /// 获取部门成员
        /// </summary>
        /// <param name="depid">部门ID</param>
        /// <param name="fetchchild">1/0：是否递归获取子部门下面的成员</param>
        /// <param name="status">0获取全部员工，1获取已关注成员列表，2获取禁用成员列表，4获取未关注成员列表。status可叠加</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string GetDepUserInfo(string depid, string fetchchild, string status, string token)
        {
            var url = string.Format(getDepUsersInfoUrl, token, depid, fetchchild, status);
            return HttpHelper.HttpGet(url);
        }

        public static Stream GetUserAvatar(string avatar)
        {
           return    HttpHelper.HttpGetFileStream(avatar);
        }

        #endregion

        #region 管理标签
        private const string createTagUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token={0}";
        private const string updateTagUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/update?access_token={0}";
        private const string delTagUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/delete?access_token={0}&tagid={1}";
        private const string getTagUsersUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token={0}&tagid={1}";
        private const string addTagUserUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token={0}";
        private const string delTaguserUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/deltagusers?access_token={0}";
        private const string getTagListUrl = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token={0}";

        /// <summary>
        /// 创建标签
        /// </summary>
        /// <param name="token"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string CreateTag(string token, WXTag model)
        {
            var url = string.Format(createTagUrl, token);
            var content = JsonConvert.SerializeObject(model);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="token"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string UpdateTag(string token, WXTag model)
        {
            var url = string.Format(updateTagUrl, token);
            var content = JsonConvert.SerializeObject(model);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="token"></param>
        /// <param name="tagid"></param>
        /// <returns></returns>
        public static string DelTag(string token, string tagid)
        {
            var url = string.Format(delTagUrl, token, tagid);
            return HttpHelper.HttpGet(url);
        }

        /// <summary>
        /// 获取标签成员
        /// </summary>
        /// <param name="token"></param>
        /// <param name="tagid"></param>
        /// <returns></returns>
        public static string GetTagUsers(string token, string tagid)
        {
            var url = string.Format(getTagUsersUrl, token, tagid);
            return HttpHelper.HttpGet(url);
        }

        /// <summary>
        /// 增加标签成员
        /// </summary>
        /// <param name="token"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string AddTagUser(string token, AddAndDelTagUserModel model)
        {
            var url = string.Format(addTagUserUrl, token);
            var content = JsonConvert.SerializeObject(model);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 删除标签成员
        /// </summary>
        /// <param name="token"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string DelTagUser(string token, AddAndDelTagUserModel model)
        {
            var url = string.Format(delTaguserUrl, token);
            var content = JsonConvert.SerializeObject(model);
            return HttpHelper.HttpPost(url, content);
        }

        /// <summary>
        /// 获取标签列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string GetTagList(string token)
        {
            return HttpHelper.HttpGet(string.Format(getTagListUrl, token));
        }


        #endregion

        #region 管理媒体文件 

        private const string uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";
        private const string getMediaUrl="https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}";
        
        public static string UploadMediaFile (string token,string fullfilename )
        {
            var fileinfo = new FileInfo(fullfilename);
            var extname = fileinfo.Extension.ToLower();
            string type = extname==".jpg" ? "image":extname==".arm"?"voice":extname==".mp4"?"video":"file";
            var url = string.Format(uploadMediaUrl,token,type);
            return HttpHelper.HttpUploadFile(url, fullfilename);
        }

        public static Stream GetMediaFile(string token,string mediaid)
        {
            var url = string.Format(getMediaUrl,token,mediaid);
            return HttpHelper.HttpGetFileStream(url);
        }


        #endregion

        #region 发送消息
        private const string sendMsgUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";

        public static string SendMsg(string token,CropMsgBase msg)
        {
            var url = string.Format(sendMsgUrl, token);
            var content = JsonConvert.SerializeObject(msg);
            return HttpHelper.HttpPost(url, content);
        }

        public static string SendMsg(CropMsgBase msg)
        {
            var url = string.Format(sendMsgUrl, CropTokenManager.GetToken());
            var content = JsonConvert.SerializeObject(msg);
            return HttpHelper.HttpPost(url, content);
        }

        #endregion

        #region 自定义菜单
        private const string createMenuUrl = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token={0}&agentid={1}";

        private const string getMenulistUrl = "https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token={0}&agentid={1}";

        private const string delMenuUrl = "https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token={0}&agentid={1}";

        public static string CreateMenu(string token, string agentid, CropMenu menu)
        {
            var url = string.Format(createMenuUrl, token, agentid);
            var content = JsonConvert.SerializeObject(menu);
            return HttpHelper.HttpPost(url, content);
        }


        public static string GetMenuList(string token, string agentid)
        {
            var url = string.Format(getMenulistUrl, token, agentid);
            return HttpHelper.HttpGet(url);
        }


        public static string DelMenu(string token, string agentid)
        {
            var url = string.Format(delMenuUrl, token, agentid);
            return HttpHelper.HttpGet(url);

        }

        #endregion

        #region OAuth2 
        private const string getUserIdUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}&agentid={2}";


        public static string GetUserInfoByOAuthCode(string code, string agentid)
        {
            var url = string.Format(getUserIdUrl, CropTokenManager.GetToken(), code, agentid);
            var jsonstr = HttpHelper.HttpGet(url);
            if (jsonstr.IndexOf("UserId") <= 0)
            {
                return "";
            }

            jsonstr = jsonstr.Substring(jsonstr.IndexOf(':') + 1);
            jsonstr = jsonstr.Substring(1);
            var userid = jsonstr.Substring(0, jsonstr.IndexOf('"'));

            return GetUserInfo(userid);

        }

        public static string GetUserIdByOAuthCode(string code, string agentid)
        {
            var url = string.Format(getUserIdUrl, CropTokenManager.GetToken(), code, agentid);
            var jsonstr = HttpHelper.HttpGet(url);
            if (jsonstr.IndexOf("UserId") <= 0)
            {
                return "";
            }

            jsonstr = jsonstr.Substring(jsonstr.IndexOf(':') + 1);
            jsonstr = jsonstr.Substring(1);
          return  jsonstr.Substring(0, jsonstr.IndexOf('"'));
        }


        #endregion
    }
}
